{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pywinauto\n",
    "from pywinauto import clipboard\n",
    "import time"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\ProgramData\\Anaconda3\\lib\\site-packages\\pywinauto\\application.py:1032: UserWarning: 32-bit application should be automated using 32-bit Python (you use 64-bit Python)\n",
      "  UserWarning)\n"
     ]
    }
   ],
   "source": [
    "app = pywinauto.Application().connect(path=r\"C:\\同花顺软件\\同花顺\\xiadan.exe\",timeout=10)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "main = app.top_window()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_left_menus_handle():\n",
    "    while True:\n",
    "        try:\n",
    "            handle = main.window(\n",
    "                control_id=129,\n",
    "                class_name='SysTreeView32'\n",
    "            )\n",
    "            # sometime can't find handle ready, must retry\n",
    "            handle.wait('ready', 2)\n",
    "            return handle\n",
    "        except:\n",
    "            pass"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<pywinauto.controls.common_controls._treeview_element at 0x209420e9c88>"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "get_left_menus_handle().get_item(['查询[F4]', '资金股票']).click()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "grid = main.window(control_id=0x417, class_name='CVirtualGridCtrl')\n",
    "\n",
    "grid.set_focus().right_click()   # 模拟右键\n",
    "pywinauto.keyboard.SendKeys('{DOWN}')\n",
    "time.sleep(0.1)\n",
    "pywinauto.keyboard.SendKeys('{DOWN}')\n",
    "time.sleep(0.1)\n",
    "pywinauto.keyboard.SendKeys('{DOWN}')\n",
    "time.sleep(0.1)\n",
    "pywinauto.keyboard.SendKeys(\"{ENTER}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 下面保存验证码\n",
    "> 注：进行此操作时，请保证验证码图片处于可视状态"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "captchas/b7d7b27e-4637-4602-8ff2-18e629dd92af.png\n",
      "captchas/0f78c6f6-674a-4899-9da8-a11aa3194312.png\n",
      "captchas/e1f0d1f8-8524-44fc-ba7a-1ba3e21545d0.png\n",
      "captchas/c4deef83-4035-4aa0-8bbe-cf51794d4b2c.png\n",
      "captchas/4f385bab-3540-4e46-85b6-021b53170089.png\n",
      "captchas/9269483e-7c06-46f5-a765-c01c57eafb38.png\n",
      "captchas/a68009e9-9fb6-4acc-8e96-c5b019c3db30.png\n",
      "captchas/09550e1c-e367-4349-afe9-2168126e4715.png\n",
      "captchas/23757f8f-91da-4bf6-96cc-dd481642f310.png\n",
      "captchas/47633d22-3390-4a13-a58e-15156e3d089b.png\n",
      "captchas/bca9e126-3de6-4122-84cc-1f4a9796efca.png\n",
      "captchas/d80fe7e2-dfb5-4131-afe1-fca60121f00c.png\n",
      "captchas/dcd2b4b8-6fdb-4433-ae49-b50fd9a5b30e.png\n",
      "captchas/2c897a09-2b7f-4601-b844-d3ab847ec501.png\n",
      "captchas/3c3acd88-1d9e-40b8-83b7-d135bdbe0423.png\n",
      "captchas/1b5f591e-5cc6-4919-8968-da5a9c1388a3.png\n",
      "captchas/f7e0e2e3-c97f-4520-b673-5043751a55cb.png\n",
      "captchas/573281b9-e21f-4fd9-a7b1-d316418d5061.png\n",
      "captchas/ff3e1928-6be9-4007-8f8d-94cb6b35b885.png\n",
      "captchas/5d867175-f6a0-4aef-b92e-1e3d503e9272.png\n"
     ]
    }
   ],
   "source": [
    "import uuid\n",
    "\n",
    "for i in range(20):\n",
    "    app.top_window().window(\n",
    "        control_id=0x965,\n",
    "        class_name='Static'\n",
    "    ).click()\n",
    "    \n",
    "    file_path = \"captchas/{uid}.png\".format(uid=str(uuid.uuid4()))\n",
    "    print(file_path)\n",
    "    app.top_window().window(\n",
    "        control_id=0x965,\n",
    "        class_name='Static'\n",
    "    ).CaptureAsImage().save(file_path)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pytesseract\n",
    "from PIL import Image"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "def recognize_captcha(img_path):\n",
    "    im = Image.open(img_path).convert(\"L\")\n",
    "    # 1. threshold the image\n",
    "    threshold = 200\n",
    "    table = []\n",
    "    for i in range(256):\n",
    "        if i < threshold:\n",
    "            table.append(0)\n",
    "        else:\n",
    "            table.append(1)\n",
    "\n",
    "    out = im.point(table, '1')\n",
    "    # out.show()\n",
    "    # 2. recognize with tesseract\n",
    "    num = pytesseract.image_to_string(out)\n",
    "    return num"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [],
   "source": [
    "img_path = \"captchas/b7d7b27e-4637-4602-8ff2-18e629dd92af.png\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAD4AAAAXCAAAAAB2CaNmAAABlUlEQVR4nNWUvUvDQBjGn5OCkMNBTLtpplqsFh2qOKjoop0cKtTFgn+CCA46u4qTf4BOfqGQyW5qB4dqQai2wS1d7EdsoSRDl3Nocsm1VCld9Jbk7n1/eZ4neQlh6GcN9EX3gjOz88zn3OhM6cYVTltX/25HidjZzZO5ZbGd7AQcWUMGUD1Khp0GtUbjYY86S/k4jcpGFKjmHBpEBsCu/Jy+Tir6BcLg2bXnLTcjiwLsZVa0qekxp34fVzA2fweOm+oq1wJZAmAMUoE21RlH3GrIACYs08EF6y2FdJt4tr4iHsAynexaBvtY8z7BaLaJP01ze9JQNQDkARs31fEE1c9Lm674Y0Q0k6pvu+EmbxQpWwJs88VmgmJs/bXsGvsUh8DIuOLAQvTwoDQl0ZY6ew9SAKPDVd5S/BJz5uF1Q2IxIB2k6Da0FXHLctTrhhUA9haxzZPwhwmgWJN5vQ23GpL3TWpnZevW4lMXGrlMUN3z6YlfxOke8W5DoWMstuafMAAs9QB7iHtc5L/8Lv4gTn7v+WF9AzMVgIP+xbtYAAAAAElFTkSuQmCC\n",
      "text/plain": [
       "<PIL.Image.Image image mode=L size=62x23 at 0x2094318C588>"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "Image.open(img_path).convert(\"L\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [],
   "source": [
    "res = recognize_captcha(img_path)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "b'6779'"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "bytes(res, \"ascii\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
